package com.example.controller;

import com.example.domain.UploadVo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(UploadVo vo) {
        try {
            // 获取文件路径
            String filePath = "/Users/liurenkui/Desktop/upload/";

            if (vo.getFile() == null || vo.getFile().getSize() < 0) {
                return "文件必须上传";
            }

            // 获取文件名
            String fileName = vo.getFile().getOriginalFilename();
            System.out.println("上传的文件名为：" + fileName);

            // 获取文件的后缀名,比如图片的jpeg,png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为：" + suffixName);

            // 文件上传后的路径
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("转换后的名称:" + fileName);

            File dest = new File(filePath + fileName);
            vo.getFile().transferTo(dest);

            return "上传成功，文件路径：" + dest.getPath();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}
